import axios from 'axios';
import { Message,Loading } from "element-ui";
import router from './router/index'

let loading;
function startLoading(){
    loading=Loading.service({
        lock:true,
        text:'努力加载中',
        background:'rgba(0,0,0,0.7)'
    })
}

function stopLoding(){
    loading.close();
}

//请求拦截
axios.interceptors.request.use(config=>{
    //加载动画
    startLoading();
    if(localStorage.eleToken){
        //设置请求头
        config.headers.Authorization=localStorage.eleToken;
    }
    return config;
},error=>{
    return Promise.reject(error)
})
//响应拦截
axios.interceptors.response.use(response=>{
    stopLoding();
    return response;
},error=>{
    //错误提醒
    stopLoding();
    Message.error(error.response.data);

    //获取错误响应码
    const{status}=error.response;
    if(status==401){
        Message.error('Token缺失,请重新登录');
        //清除token
        localStorage.removeItem('eleToken');
        router.push('/login');
    }
    return Promise.reject(error);
})

export default axios;